<template>
    <div style="min-height: 100vh">
        <!-- 头部区域开始 -->
        <UserNav/>
        <!-- 头部区域结束 -->
        <!--  下方区域开始 -->
        <div class="content-detail-container">
            <!-- 点赞收藏等区域开始 ：左 -->
            <div class="action-buttons">
                <div style="position: relative">
                    <el-button class="action-buttons-item"  @click="handleLike">
                        <img v-if="isLiked" src="@/assets/icon_svg/实心赞.svg" alt="实心赞" style="width: 22px; height: 22px">
                        <img v-else src="@/assets/icon_svg/赞.svg" alt="赞" style="width: 22px; height: 22px">
                        <span class="count">{{ detail.likes }}</span>
                    </el-button>
                    <el-button class="action-buttons-item" @click="handleCollect">
                        <img v-if="isCollected" src="@/assets/icon_svg/实心收藏.svg" alt="赞" style="width: 22px; height: 22px">
                        <img v-else src="@/assets/icon_svg/_收藏.svg" alt="收藏" style="width: 20px; height: 20px">
                        <span class="count">{{ detail.collections }}</span>
                    </el-button>
                    <el-button class="action-buttons-item" @click="">
                        <img src="@/assets/icon_svg/转发.svg" alt="收藏" style="width: 20px; height: 20px">
                    </el-button>
                    <el-button class="action-buttons-item" @click="">
                        <img src="@/assets/icon_svg/举报.svg" alt="举报" style="width: 20px; height: 20px">
                    </el-button>
                </div>
            </div>
            <!-- 点赞收藏等区域结束 -->

            <!--  内容详情区域开始 -->
            <div class="content-detail-auto">
                <div style="position: relative">
                    <!-- 标题 -->
                    <h1 style="text-align: center">{{ detail.title }}</h1>
                    <!-- 文章信息区域（预留）：置于内容底部靠左-->
                    <div class="user-info-area" style="border-bottom: 2px #f5f4f1 solid">
                        <!-- 用户信息区域 靠左 -->
                        <div class="interaction-info">
                            <el-button type="primary" v-if="detail.contentType === 'QUESTION'"><el-icon :size="18"><EditPen/></el-icon>&nbsp;&nbsp;写回答</el-button>
                            <span>{{detail.user.username}}</span>
                            <span class="icon-item"><img src="@/assets/icon_svg/浏览量.svg" alt="icon" style="width: 20px; height: 20px; font-size: 16px">{{ detail.views }}</span>
                        </div>
                        <!--分类标签区域 靠右-->
                        <div  class="blog-meta">
                            <span v-if="detail.tags"><el-tag v-for="tag in detail.tags.split(',')" :key="tag" type="success">{{ tag }}</el-tag></span>
                            <span v-if="detail.category && detail.category.categoryName"><el-tag type="info">{{ detail.category.categoryName }}</el-tag></span>
                            <span>发布于{{ detail.created_at }}</span>
                        </div>
                    </div>
                    <!-- 封面图片（右） -->
                    <div class="blog-cover" v-if="detail.cover">
                        <el-image style="height: 100%; border-radius: 0.375rem" :src="detail.cover" fit="cover" :preview-src-list="[detail.cover]"/>
                    </div>
                    <!-- 内容 -->
                    <div class="blog-desc" v-html="detail.content"></div>
                </div>
                <!-- 评论区域开始 -->
                <div class="comment-section">
                    <h3 style="padding: 10px" v-if="detail.contentType === 'QUESTION'">所有回答 ({{ commentList?.length || 0 }})</h3>
                    <h3 style="padding: 10px" v-else>评论区 ({{ commentList?.length || 0 }})</h3>
                    <!-- 评论输入区域  -->
                    <div style="display: flex; margin: 20px 20px 0 20px; flex-direction: column" v-if="isLoggedIn">
                        <el-avatar :src="detail.user.profile_photo_path" shape="circle" :size="35" style="margin-right: 10px"
                        ></el-avatar>
                        <TextEditor
                            ref="newCommentEditor"
                            placeholder="发表你的评论..."
                            @getContent="handleNewCommentContent"
                            style="height: 100px!important;"
                        />
                        <el-button type="primary" @click="publishNewComment" :loading="publishing" style="width: 100px; position: absolute; right: 20px ">发 送</el-button>
                    </div>
                    <!-- 评论列表: 使用递归组件渲染多级评论 -->
                    <div v-if="isCommentData" style="margin: 0 20px 20px 20px">
                        <CommentItem
                            v-for="comment in commentList"
                            :key="comment?.commentId || 0"
                            :comment="comment"
                            @reply="handleReply"
                            @addReply="addNewReply"
                        >
                        </CommentItem>
                    </div>
                    <div v-else class="autobox-container-ar" style="display: flex; align-items: center; justify-content: center" >
                        <img src="@/assets/imge/暂无数据.jpg" alt="暂无数据" style="width: 280px; height: 280px">
                    </div>
                <!-- 评论区域结束 -->
            </div>
            <!--  内容详情区域结束 -->
            </div>
            <!-- 作者信息区域开始 -->
            <div class="content-user">
                <router-link :to="`/personalhome/${detail.userId}`">
                    <!-- 用户头像及用户名 -->
                    <div style="display: flex; align-items: center; justify-content: center; margin: 20px 0 30px 0; gap: 20px">
                        <el-avatar :src="detail.user.profile_photo_path" shape="circle" :size="45" @error="errorHandler">
                            <img
                                src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                                alt="加载错误"/> <!--图片加载失败的回退行为-->
                        </el-avatar>
                        <strong style="font-size: 17px">{{ detail.user.username }}</strong>
                    </div>
                </router-link>
                <!-- 文章数 关注数量 粉丝数量 -->
                <div>

                </div>
                <!-- 关注私信按钮 -->
                <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 20px">
                    <el-button type="primary" style="width: 100px">关注</el-button>
                    <el-button style="width: 100px" @click="privateMessage">私信</el-button>
                </div>
                <!-- 作者其他文章 -->
                <div >
                    <!-- 标题区域 -->
                    <div style="width: 200px; height: 35px; border-bottom: 1px #cccbc8 solid; text-align: center;  margin: 0 auto; font-weight: 500">
                        <span >作者其他相关内容</span>
                    </div>
                    <!-- 内容区域 -->
                    <div style="width: 240px; max-height: 350px; min-height: 200px; background-color: #fffefb">
                        <div class="blog-item" v-for="item in newContent" :key="item.contentId">
                            <router-link :to="`/contentdetail/${item.contentType}/${item.contentId}`">
                                <!-- 内容主体区域 -->
                                <div style="display: flex; align-items: center; justify-content: space-between">
                                    <!-- 标题 -->
                                    <strong class="blog-title">{{ item.title }}</strong>
                                </div>
                            </router-link>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 作者信息区域结束 -->
        </div>
        <!-- 下方区域结束 -->
    </div>
    <div v-if="isLoading" class="load-more-tip">加载中...</div>
</template>

<script setup>
import UserNav from "@/components/UserNav.vue";
import { ref, reactive, onMounted,nextTick } from 'vue'
import {useRoute, useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import request from "@/utils/request.js";
import {EditPen} from "@element-plus/icons-vue";
import CommentItem from "@/components/CommentItem.vue";
import TextEditor from "@/components/TextEditor.vue";


const isLoading = ref(false)
const router = useRouter()

// 生命周期钩子：页面加载时获取详情数据
onMounted(() => {
    // 加载内容详情
    loadContentDetail(contentId ,contentType);
    // 加载评论列表
    fetchCommentList (contentId ,contentType);
    // 增加浏览量
    updateViews(contentData);
    const imgElements = document.querySelectorAll('.blog-desc img');
    imgElements.forEach((img) => {
        // 设置图片的公共属性，例如添加class
        img.classList.add('custom-img-class');
        // 设置图片的宽度和高度
        img.style.width = 'auto';
        img.style.height = '400px';
        img.style.display = 'flex'
        img.style.margin = '0 auto'
        // 给图片添加点击事件
        img.addEventListener('click', () => {
            console.log('图片被点击了');
        });
    });
});

const errorHandler = () => true //图片加载失败的回退行为

//获取本地存储中的用户信息
let user;
const loginUser = localStorage.getItem('code_user');
if (loginUser) {
    // 将拿到的Json数据转化为JavaScript对象
    user = JSON.parse(loginUser);
}


// 获取路由参数中的内容ID
const route = useRoute();
const contentId = route.params.id;
const contentType = route.params.type;

// 详情数据
let detail = reactive({
    user: {
        user_id: null,
        username: '',
        profile_photo_path: '',
    },
    likeStates: false,
    collectStates: false,
});
// 内容数据
const contentData = {
    userId: user?.user_id || null,  // 当前浏览内容的用户
    targetId: contentId,
    targetType: contentType
}

// 获取内容详情
const loadContentDetail = (contentId ,contentType) => {
    try {
        isLoading.value = true
        request.get("/api/content/detail/" + contentType + "/" + contentId, {
            params: {
                userId: user?.user_id || null// 登录的用户
            }
        }).then(res => {
            if (res.code === '200') {
                // 使用 Object.assign 或 ... 展开运算符更新 detail
                Object.assign(detail, res.data);
                detail = res.data;  // 初始化作者Id
                // 初始化点赞/收藏数量
                detail.likes = res.data.likes;
                detail.collections = res.data.collections;
                detail.views = res.data.views;  // 初始化浏览量
                // 初始化该用户对于本内容的点赞/收藏状态
                isLiked.value = res.data.likeStates;
                isCollected.value = res.data.collectStates;
            } else {
                ElMessage.error(res.msg);
            }
            // 加载用户的所有文章
            selectContentByUser();
        })
    } catch (error) {
        ElMessage.error('加载详情失败，请重试');
        console.error(error);
    } finally {
        isLoading.value = false
    }
};


// 增加浏览量
const updateViews = async (views) => {
    try {
        await request.post(`/api/content/updateViews`, views).then(res => {
            if (res.code === '200') {
                detail.views = res.data.views
            }
        })
    } catch (error) {
        console.error('浏览量更新失败', error);
    }
};

// 内容总数
let contentNum = ref(0)
// 作者同类型文章列表
let newContent = ref([])
// 查询该用户的所有文章，展示前7篇(待扩展)
const selectContentByUser = () => {
    request.get('/api/content/contentByUser/' + contentType, {
        params: {
            userId: detail.userId  // 作者
        }
    }).then(res => {
        if (res.code === '200') {
            newContent.value = res.data  // 保存所有数据
            contentNum.value = newContent.value.length  // 内容总数
        } else {
            ElMessage.error("查询用户所有内容失败")
        }
    })
}

// 评论相关数据


// 评论列表数据
const commentList = ref([]);
const isCommentData = ref(false);
const isLoggedIn = ref(true); // 是否已登录
const newCommentContent = ref('');
const newCommentEditor = ref();
const publishing = ref(false);



// 获取评论列表
const fetchCommentList = (contentId ,contentType) => {
    try {
        request.get(`/api/comment/commentList/${contentType}/${contentId}`).then(res => {
            if (res.code === '200') {
                commentList.value = res.data;
                isCommentData.value = true  ;// 修改数据展示状态
            }
        })
    } catch (error) {
        console.error('评论加载失败', error);
    }
};
// 处理新评论内容
const handleNewCommentContent = (content) => {
    newCommentContent.value = content;
};
// 发布新评论
const publishNewComment = async () => {
    await nextTick(); // 确保 DOM 更新后再调用 exposeContent
    if (newCommentEditor.value) {
        newCommentEditor.value.exposeContent();
    }  // 编辑器引用获取内容，之后通过handleNewCommentContent事件将内容传递给newCommentContent.value
    if (!newCommentContent.value) {
        ElMessage.warning('评论内容不能为空');
        return;
    }
    publishing.value = true;
    // 数据
    const newComment = {
        userId: user.user_id, // 当前登录用户ID
        targetId: contentId,
        targetType: contentType,
        parentId: null,
        content: newCommentContent.value,
    };
    try {
        request.post('/api/comment/addComment', newComment).then(res => {
            if (res.code === '200') {
                ElMessage.success('评论发布成功');
                location.reload()
            } else {
                ElMessage.error("评论未发送")
            }
        })
    } catch (error) {
        console.error('发布评论失败:', error);
        ElMessage.error('评论发布失败');
    } finally {
        publishing.value = false;
    }
};
// 处理回复事件
const handleReply = (commentId) => {
    console.log('准备回复评论:', commentId);
    // 这里可以添加跳转到回复框或其他逻辑
};
// 添加新回复
const addNewReply = (newReply) => {
    request.post('/api/comment/addComment', newReply).then(res => {
        if (res.code === '200') {
            ElMessage.success("回复成功")
            location.reload()
        } else {
            ElMessage.error("回复未发送")
        }
    })
};

// 点赞状态
const isLiked = ref(false);
// 点赞功能
const handleLike = async () => {
    isLiked.value  = !isLiked.value // 点赞状态
    isLiked.value ? submitLike() : cancelLike(contentData) // 取消点赞 、 点赞
};
const submitLike = () => {
    try {
        request.post(`/api/content/addLike`, {
            userId: user.user_id,
            targetId: contentId,
            targetType: contentType,
        }).then(res => {
            if (res.code === '200') {
                detail.likes = res.data.likes; // 更新点赞数
                isLiked.value = true;
                ElMessage.success('点赞成功');
                // 给作者发送点赞通知
                const message = {
                    senderId: user.user_id,  // 当前登录用户
                    receiverId: detail.userId, // 作者
                    targetId: contentId,
                    targetType: contentType,
                    title: null,
                    content: '点赞了你的内容',
                    messageType: 'CONTENT'
                };
                request.post('/api/interaction/addInteraction', message).then(res => {
                    if (res.code === '200') {
                        console.log('推送成功')
                    } else {
                        console.log('推送失败')
                    }
                })
            }
        })
    } catch (error) {
        ElMessage.error('点赞失败，请重试');
    }
}
const cancelLike = (like) => {
    try {
        request.post(`/api/content/deleteLike`, like).then(res => {
            if (res.code === '200') {
                detail.likes = res.data.likes; // 更新点赞数
                isLiked.value = false;
                ElMessage.success('点赞已取消');
            }
        })
    } catch (error) {
        ElMessage.error('点赞失败，请重试');
    }
}

// 收藏状态
const isCollected = ref(false);
// 收藏功能
const handleCollect = async () => {
    isCollected.value  = !isCollected.value // 点赞状态
    isCollected.value ? submitCollect() : cancelCollect(contentData) // 取消点赞 、 点赞
};
const submitCollect = () => {
    try {
        request.post(`/api/content/addCollect`, {
            userId: user.user_id,
            targetId: contentId,
            targetType: contentType,
        }).then(res => {
            if (res.code === '200') {
                detail.collections = res.data.collections; // 更新收藏数
                isCollected.value = true;
                ElMessage.success('收藏成功');
            }
        })
    } catch (error) {
        ElMessage.error('收藏失败，请重试');
    }
}
const cancelCollect = (collect) => {
    try {
        request.post(`/api/content/deleteCollect`, collect).then(res => {
            if (res.code === '200') {
                detail.collections = res.data.collections; // 更新收藏数
                isCollected.value = false; // 更新收藏状态
                ElMessage.success('已取消收藏');
            }
        })
    } catch (error) {
        ElMessage.error('收藏失败，请重试');
    }
}
// 私信跳转
const privateMessage = () => {
    router.push('/messagecenter/privatemessage/' + detail.userId)
}
</script>
<script>
// 导出默认配置，用于设置组件的 key 属性
export default {
    props: ['key'],
    // 因为在 setup 语法糖中已经处理了大部分逻辑，这里可以为空
};
</script>
<style scoped>
/*整体内容区域样式*/
.content-detail-container {
    display: flex;
    width: 1260px;
    margin: 0 auto;
    position: relative;
    top: 100px;
    padding: 20px;
    min-height: 100vh;
}
/*内容区域样式*/
.content-detail-auto {
    width: 864px;
    position: absolute;
    top: 0;
    left: 120px;
    background-color: #fffefb;
}
/*作者信息区域样式*/
.content-user {
    width: 240px;
    position: fixed;
    top: 100px;
    right: 50px;
    background-color: #fffefb;
    z-index: 999;
}
.new-content {
    width: 240px;
    position: fixed;
    top: 300px;
    right: 90px;
    background-color: #fffefb;
}
/*点赞收藏按钮样式*/
.action-buttons {
    position: fixed;
    top: 130px;
    width: 80px;
    display: flex;
    flex-direction: column; /*垂直排列*/
    gap: 10px; /* 垂直间距 */
    padding: 10px;
    background: transparent; /* 透明背景 */
}
/*计数样式*/
.count {
    margin-left: 5px;
    font-size: 0.95em;
    color: #666;
    position: absolute;
    top: 5px;
    right: 0;
}
.action-buttons-item {
    position: relative;
    width: 60px;
    height: 60px;
    border: none;
    border-radius: 50%; /* 圆形按钮 */
    display: flex;
    flex-direction: column;
    align-items: center; /* 水平居中 */
    justify-content: center; /* 垂直居中 */
    gap: 4px; /* 图标与文字间距 */
    font-size: 12px;
    color: #333;
    transition: background-color 0.3s ease; /* 平滑过渡 */
    cursor: pointer;
    margin-left: 0;
    margin-top: 20px;
}
.action-buttons-item:hover {
    background-color: #f3f4f6; /* 悬停背景色 */
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 悬停阴影 */
}

/* 图标样式 */
.action-buttons-item img {
    display: block; /* 清除默认基线对齐 */
}
/*评论列表样式*/
.comment-section {
    margin-top: 5px;
    background-color: #fffefb;
    width: 864px;
    position: absolute;
    left: 0;
    min-height: 700px;
}

/*互动信息区样式*/
.interaction-info {
    display: flex;
    align-items: center;
    gap: 25px;
    font-size: 14px;
    color: #666;
}
.icon-item {
    display: flex;
    align-items: center;
    gap: 5px;
}
/* 用户信息区域样式 */
.user-info-area {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
}
/*分类标签样式*/
.blog-meta {
    position: absolute;
    right: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 14px;
    color: #666;
    margin-left: 10px;
}
/* 封面图片样式 */
.blog-cover {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 280px;
    text-align: center;
    margin: 10px 0
}
::v-deep .blog-desc img {  /*深度选择器 ::v-deep 来穿透作用域,用来选择使用v-html插入的元素*/
    width: auto;
    height: 400px;
    display: flex;
    margin: 0 auto;
}
::v-deep .blog-desc {
    padding: 20px 40px;
}

/*卡片样式*/
.blog-item {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    gap: 10px;
    margin: 5px;
    min-height: 30px;
    transition: transform 0.3s, box-shadow 0.3s;
}
.blog-item:hover {
    background-color: #f5f4f1;
    border-radius: 5px;
    color: #1677ff;
}
/*标题样式*/
.blog-title {
    padding: 5px;
    font-size: 13px;
    font-weight: 400;
    color: #1a1a1a;
    margin: 2px auto;
}
.blog-title:hover {
    color: #1677ff;
}
</style>